package comprehension.cn.edu.scau.cmi.guihao.comprehension.dao;

import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import comprehension.cn.edu.scau.cmi.guihao.comprehension.domain.Student;
import comprehension.cn.edu.scau.cmi.guihao.comprehension.util.ScauCmiHibernateSessionFactoryUtil;



public class StudentDAO {
	private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	// property constants
	public static final String NAME = "name";
//	dao依赖hibernate session对象。使用spring封装该属性。
	private Session session=null;

	public boolean save(Student transientInstance) {
		try {
//			如果
			if(session==null) {
				getSession();	
			}
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
			return true;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	private Session getSession() {
		session=ScauCmiHibernateSessionFactoryUtil.getSession();
		return session;
	}
	
	public boolean delete(Student persistentInstance) {
		log.debug("deleting Student instance");
		try {
			if(session==null) {
				getSession();	
			}
			Transaction transaction = session.beginTransaction();
			Student student = (Student) session.get("comprehension.cn.edu.scau.cmi.guihao.comprehension.domain.Student", persistentInstance.getId());
			session.delete(student);
			transaction.commit();
			log.debug("delete successful");
			return true;
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public boolean update(Student persistentInstance) {
		log.debug("deleting Student instance");
		try {
			if(session==null) {
				getSession();	
			}
			Transaction transaction = session.beginTransaction();
			session.update(persistentInstance);
			transaction.commit();
			return true;
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	
	
	public Student findById(java.lang.Long id) {
		log.debug("getting Student instance with id: " + id);
		try {
			if(session==null) {
				getSession();
			}
			Student instance = (Student) session.get("comprehension.cn.edu.scau.cmi.guihao.comprehension.domain.Student", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findAll() {
		log.debug("finding all Student instances");
		try {
			if(session==null) {
				getSession();
			}
			String queryString = "from Student";
			Query queryObject = session.createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
}